<template>
	<el-dialog :close-on-click-modal="false" :title="form.roleId ? '编辑角色' : '创建角色'" width="347px" draggable v-model="visible">
		<el-form :model="form" :rules="dataRules" label-width="90px" ref="dataFormRef" v-loading="loading">
			<el-form-item label="角色名称" prop="roleName">
				<el-input :placeholder="$t('sysrole.please_enter_a_role_name')" v-model="form.roleName"></el-input>
			</el-form-item>
			<el-form-item prop="roleDo" label="角色属性" v-if="typeForm.includes('2')">
				<el-checkbox v-model="form.managerFlag" :true-value="1" :false-value="0"> 是否管理员 </el-checkbox>
				<el-checkbox v-model="form.testerFlag" :true-value="1" :false-value="0"> 是否测试员 </el-checkbox>
			</el-form-item>
			<el-form-item label="功能描述" prop="funcTypes" v-if="typeForm.includes('2')">
				<el-checkbox-group v-model="form.funcTypes">
					<el-checkbox label="0">基础功能</el-checkbox>
					<el-checkbox label="1">订阅功能</el-checkbox>
				</el-checkbox-group>
			</el-form-item>

			<el-form-item label="空间设置" prop="spaceSize" v-if="typeForm.includes('3')">
				<div class="space-slider-container">
					<el-slider :disabled="form.unlimited" v-model="form.spaceSize" :max="5368709120" :step="104857600" :format-tooltip="formatTooltip" />
					<div class="slider-tick-container">
						<span class="tick-label">0.5G</span>
						<span class="tick-label">1G</span>
						<span class="tick-label">2G</span>
						<span class="tick-label">3G</span>
						<span class="tick-label">4G</span>
						<span class="tick-label">5G</span>
					</div>
					<el-checkbox class="mt-5" @change="handleUnlimitedChange" v-model="form.unlimited">无限制</el-checkbox>
				</div>
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button class="btnClose" @click="visible = false">{{ $t('common.cancelButtonText') }}</el-button>
				<el-button class="btnSave" @click="onSubmit" :disabled="loading">{{ $t('common.confirmButtonText') }}</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script lang="ts" name="systemRoleDialog" setup>
import { rule } from '/@/utils/validate';
import { deptTree } from '/@/api/admin/dept';
import { useMessage } from '/@/hooks/message';
import { addObj, getObj, putObj, validateRoleName } from '/@/api/admin/role';
import { useI18n } from 'vue-i18n';
import { generateUUID } from '/@/utils/other';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

const { t } = useI18n();
const typeForm = ref([]);
// 定义变量内容
const dataFormRef = ref();
const deptTreeRef = ref();
const visible = ref(false);
const loading = ref(false);

// 提交表单数据
const form = reactive({
	roleId: '',
	roleName: '',
	managerFlag: 0,
	testerFlag: 0,
	roleDo: '',
	funcTypes: ['0'],
	unlimited: false,
	spaceSize: 524288000, // 默认1G
});
// 页面对应元数据
const dataForm = reactive({
	deptData: [],
	checkedDsScope: [],
	deptProps: {
		children: 'children',
		label: 'name',
		value: 'id',
	},
});

// 定义校验规则
const dataRules = ref({
	roleName: [
		{ required: true, message: '角色名称不能为空', trigger: 'blur' },
		{ min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' },
		{
			validator: (rule: any, value: any, callback: any) => {
				validateRoleName(rule, value, callback, form.roleId !== '');
			},
			trigger: 'blur',
		},
	],
	spaceSize: [{ required: true, message: '请设置空间大小', trigger: 'change' }],
	// roleCode: [
	// 	{ required: true, message: '角色编码不能为空', trigger: 'blur' },
	// 	{ min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' },
	// 	{
	// 		validator: (rule: any, value: any, callback: any) => {
	// 			const reg = /^[A-Za-z_]+$/;
	// 			if (!reg.test(value)) {
	// 				callback(new Error('角色编码只能包含英文和下划线'));
	// 			} else {
	// 				callback();
	// 			}
	// 		},
	// 		trigger: 'blur',
	// 	},
	// ],
	roleDo: [
		{
			required: true,
			validator: (rule: any, value: any, callback: any) => {
				// 验证至少选择一个 checkbox
				if (!form.managerFlag && !form.testerFlag) {
					callback(new Error('请至少选择一个角色属性'));
				} else {
					callback();
				}
			},
			trigger: 'change',
		},
	],
	funcTypes: [{ required: true, message: '请至少选择一个功能类型', type: 'array', trigger: 'change' }],
});
// 打开弹窗=
const openDialog = (row: string) => {
	visible.value = true;
	typeForm.value = ['2', '3'];
	form.roleId = '';
	nextTick(() => {
		dataFormRef.value.resetFields();
	});
	// getDeptData();
};

const editDialog = (row: any, type: string) => {
	Object.keys(form).forEach((key) => {
		// @ts-ignore
		form[key] = undefined;
	});
	Object.assign(form, row);
	visible.value = true;
	typeForm.value = [type];
	if (row.funcType) {
		form.funcTypes = row.funcType.split(',');
	} else {
		form.funcTypes = [];
	}
	if (row.spaceSize == -1) {
		form.unlimited = true;
		form.spaceSize = 0; // 设置一个默认值用于显示
	} else {
		form.unlimited = false;
		form.spaceSize = Number(form.spaceSize);
	}
	form.managerFlag = row.managerFlag == 1 ? true : false;
	form.testerFlag = row.testerFlag == 1 ? true : false;

	nextTick(() => {
		if (dataFormRef.value) {
			dataFormRef.value.clearValidate();
		}
	});
};
// 提交
const onSubmit = async () => {
	const valid = await dataFormRef.value.validate().catch(() => {});
	if (!valid) return false;
	const submitForm = {
		...form,
		roleCode: generateUUID(),
		managerFlag: form.managerFlag ? 1 : 0,
		testerFlag: form.testerFlag ? 1 : 0,
		spaceSize: form.unlimited ? -1 : form.spaceSize,
	};
	try {
		loading.value = true;
		delete submitForm.roleDo;
		delete submitForm.unlimited;
		delete submitForm.spaceSizeName;
		if (submitForm.roleId) {
			await putObj(submitForm);
		} else {
			delete submitForm.roleId;
			await addObj(submitForm);
		}
		useMessage().success(t(submitForm.roleId ? '修改成功' : '新增成功'));
		visible.value = false;
		emit('refresh');
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};

const handleUnlimitedChange = (value: any) => {
	if (value) {
		// 当选择无限制时，可以将空间大小设置为一个特殊值
		form.spaceSize = -1; // 或者其他表示无限制的值
	}
	// 当取消无限制时，不需要特别处理，保持当前的 spaceSize 值
};
const formatTooltip = (value: number) => {
	if (value >= 1073741824) {
		return `${(value / 1073741824).toFixed(2)}G`;
	} else if (value >= 1048576) {
		return `${(value / 1048576).toFixed(2)}M`;
	} else {
		return `${value}B`;
	}
};

// 初始化角色数据
const getRoleData = (row: any) => {
	// 获取部门数据
	getObj({ roleId: row.id, roleDesc: row.roleDesc, roleCode: row.roleCode, roleName: row.roleName }).then((res: any) => {
		Object.assign(form, res.data);
		if (res.data.dsScope) {
			dataForm.checkedDsScope = res.data.dsScope.split(',');
		} else {
			dataForm.checkedDsScope = [];
		}
	});
};

// 获取菜单结构数据
const getDeptData = () => {
	deptTree().then((res: any) => {
		dataForm.deptData = res.data;
	});
};

// 暴露变量
defineExpose({
	openDialog,
	editDialog,
});
</script>
<style lang="scss" scoped>
:deep(.el-form-item--default) {
	margin-bottom: 12px;
}
.space-slider-container {
	position: relative;
	width: 100%;

	.slider-tick-container {
		position: absolute;
		top: 48%;
		left: 0;
		width: 100%;
		display: flex;
		justify-content: space-between;
		font-size: 12px;
		color: #606266;

		.tick-label {
			transform: translateY(-50%);
		}
	}

	.el-slider__runway {
		height: 8px;
		border-radius: 4px;
		background-color: #e4e7ed;
	}

	.el-slider__bar {
		background-color: #409eff;
		border-radius: 4px;
	}

	.el-slider__button {
		width: 16px;
		height: 16px;
		border-radius: 50%;
		border: 2px solid #409eff;
		background-color: white;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
	}

	.el-slider__input {
		width: 80px;
		margin-left: 10px;
	}
}
</style>
